package com.ruoyi.fitsculpt.interceptor;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.fitsculpt.utils.TokenUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 使用专门的小程序token header
        String token = request.getHeader("token");

        if (token == null || token.isEmpty()) {
            responseError(response, "未登录", 401);
            return false;
        }

        // 验证token
        Long userId = TokenUtils.getUserIdFromToken(token);
        if (userId == null) {
            responseError(response, "token无效", 401);
            return false;
        }

        // 将用户ID存入request
        request.setAttribute("userId", userId);
        return true;
    }

    private void responseError(HttpServletResponse response, String message, int statusCode) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(200);
        PrintWriter out = response.getWriter();
        out.write(JSON.toJSONString(AjaxResult.error(statusCode, message)));
        out.flush();
        out.close();
    }
}
